#!/sbin/openrc-run
# Copyright 1999-2016 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

depend() {
	need capi
}

checkconfig() {
	local DEFAULT_OUTPUT_FORMAT="HYLAFAX"
	local DEFAULT_VIRTUAL_DEVICE="faxCAPI"
	local DEFAULT_RECEIVE_DIR="/var/spool/fax"
	local DEFAULT_CONFIG_FILE="/var/spool/fax/etc/config.faxCAPI"

	[ -n "${CONFIG_FILE}" ] || CONFIG_FILE="${DEFAULT_CONFIG_FILE}"
	[ -n "${OUTPUT_FORMAT}" ] || OUTPUT_FORMAT="${DEFAULT_OUTPUT_FORMAT}"
	[ -n "${VIRTUAL_DEVICE}" ] || VIRTUAL_DEVICE="${DEFAULT_VIRTUAL_DEVICE}"
	[ "${OUTPUT_FORMAT}" = "HYLAFAX" ] || DEFAULT_RECEIVE_DIR="/var/spool/fax/recvq"
	[ -n "${RECEIVE_DIR}" ] || RECEIVE_DIR="${DEFAULT_RECEIVE_DIR}"

	if [ ! -f "${CONFIG_FILE}" ]; then
		eerror "You're missing ${CONFIG_FILE}"
		return 1
	fi

	OPTIONS=""
	PIDFILE="/var/run/c2faxrecv.pid"

	[ "${ACTIVATE_LOGGING}" = "yes" ] && OPTIONS="${OPTIONS} -L"

	[ "${OUTPUT_FORMAT}" = "${DEFAULT_OUTPUT_FORMAT}" ] || \
	OPTIONS="${OPTIONS} -f ${OUTPUT_FORMAT}"

	[ "${CONFIG_FILE}" = "${DEFAULT_CONFIG_FILE}" ] || \
	OPTIONS="${OPTIONS} -C ${CONFIG_FILE}"

	[ "${OUTPUT_FORMAT}" = "HYLAFAX" -a "${RECEIVE_DIR}" = "${DEFAULT_RECEIVE_DIR}" ] || \
	OPTIONS="${OPTIONS} -q ${RECEIVE_DIR}"

	if [ "${VIRTUAL_DEVICE}" != "${DEFAULT_VIRTUAL_DEVICE}" ]; then
		PIDFILE="/var/run/c2faxrecv.${VIRTUAL_DEVICE}.pid"
		OPTIONS="${OPTIONS} ${VIRTUAL_DEVICE}"
	fi
}

start() {
	checkconfig || return 1

	ebegin "Starting CAPI4HylaFAX for ${VIRTUAL_DEVICE}"
	start-stop-daemon -b -m --quiet --start --pidfile ${PIDFILE} \
		--exec /usr/bin/c2faxrecv -- ${OPTIONS}
	eend $?
}

stop() {
	checkconfig || return 1

	ebegin "Stopping CAPI4HylaFAX for ${VIRTUAL_DEVICE}"
	start-stop-daemon >/dev/null --quiet --stop --pidfile ${PIDFILE} --retry 10 && \
	/bin/rm -f ${PIDFILE}
	eend $?
}

